import React from "react";
import {Tree, Spin, Input, Table, message, Button, Modal, Form, Popconfirm} from "antd";
import {connect} from "dva";
// import { equals } from "@cbd/utils";
import styles from "./TreeSelect.less";

import {openNotificationWithIcon} from "../../utils/comm.js";

const {TreeNode} = Tree;
const {Search} = Input;

const columnsEmployee = [
  {
    title: "用户工号",
    dataIndex: "employeeCode",
    key: "employeeCode",
  },
  {
    title: "用户姓名",
    dataIndex: "employeeName",
    key: "employeeName",
  },
  {
    title: "所属组织",
    dataIndex: "orgName",
    key: "orgName",
    render: (text, record) =>
      record.orgList.map(item => item.orgName).join("，"),
  },
];

const columnsRole = [
  {
    title: "角色名称",
    dataIndex: "roleName",
    key: "roleName",
  },
];

const columnsGroup = [
  {
    title: "组织名称",
    dataIndex: "groupName",
    key: "groupName",
  },
];

const columnsPosition = [
  {
    title: "岗位名称",
    dataIndex: "positionName",
    key: "positionName",
  },
];

@connect(({usertreeSelect, loading}) => ({
  loading,
  usertreeSelectStore: usertreeSelect,
}))
@Form.create()
class TreeSelect extends React.Component {
  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon;
    this.selectData = [];
    this.loadedKeys = [];
    this.selectedKeysInvert = [];
    this.state = {
      treeData: [],
      selectedKeys: [],
      columns: [],
      keyWord: "",
      pageNum: 1,
      pageSize: 6,
      totalCount: 0,
      listData: [],
      selectedRowKeys: [],
      visible: false,
    };
  }

  componentDidMount() {
    const {type, defaultSelectData} = this.props;
    this.getTreeThis();

    if (type === "STA") {
      this.setState({
        columns: columnsEmployee,
        totalCount: 0,
        listData: [],
        pageNum: 1,
        selectedRowKeys:
          (Array.isArray(defaultSelectData) &&
            defaultSelectData.filter(d => d.type === "STA").map(v => v.code)) ||
          [],
      });
    } else if (type === "ROL") {
      this.setState(
        {
          columns: columnsRole,
          totalCount: 0,
          listData: [],
          pageNum: 1,
          selectedRowKeys:
            (Array.isArray(defaultSelectData) &&
              defaultSelectData
                .filter(d => d.type === "ROL")
                .map(v => v.code)) ||
            [],
        },
        () => {
          this.onSearch();
        },
      );
    } else if (type === "GROUP") {
      this.setState(
        {
          columns: columnsGroup,
          totalCount: 0,
          listData: [],
          pageNum: 1,
          selectedRowKeys:
            (Array.isArray(defaultSelectData) &&
              defaultSelectData
                .filter(d => d.type === "GROUP")
                .map(v => v.code)) ||
            [],
        },
        () => {
          this.onSearch();
        },
      );
    } else if (type === "POSITION") {
      this.setState(
        {
          columns: columnsPosition,
          totalCount: 0,
          listData: [],
          pageNum: 1,
          selectedRowKeys:
            (Array.isArray(defaultSelectData) &&
              defaultSelectData
                .filter(d => d.type === "POSITION")
                .map(v => v.code)) ||
            [],
        },
        () => {
          this.onSearch();
        },
      );
    } else if (type === "RELATIONSHIP") {
      this.getUserRelationShipList();
    } else if (type === "FUNCTION") {
      this.getAllFunctionConfigList();
    } else if (type === "ORG") {
      this.getRootOrg();
    }
  }

  componentDidUpdate(prevProps) {
    const {appId, type} = this.props;
    if (prevProps.appId !== appId) {
      if (type === "RELATIONSHIP") {
        this.getUserRelationShipList();
      }
      if (type === "FUNCTION") {
        this.getAllFunctionConfigList();
      }
    }
  }

  componentWillUnmount() {
    const {dispatch} = this.props;
    dispatch({type: "usertreeSelect/clearData"});
  }

  getRootOrg = () => {
    const {dispatch} = this.props;
    if (!dispatch) return;
    dispatch({
      type: "usertreeSelect/getRootOrg",
      payload: {},
    }).then(({errCode, datas}) => {
      if (errCode !== 0) {
        this.openNotificationWithIcon("error", "", "获取根组织信息失败");
      }
      const newDatas = Array.isArray(datas) ? datas : [datas];
      this.loadedKeys = this.loadedKeys.concat(newDatas);
      this.setState({treeData: newDatas});
      this.setTreeSelectData(this.selectedKeysInvert, this.selectData);
    });
  };

  getCandidateGroups = () => {
    const {dispatch} = this.props;
    const {pageNum, pageSize, keyWord} = this.state;
    if (!dispatch) return;
    dispatch({
      type: "FlowChart/getUserRolePageList",
      payload: {roleName: keyWord, pageNo: pageNum, pageSize},
    }).then(({errCode, datas = [], totalCount = 0}) => {
      if (errCode !== 0) {
        this.openNotificationWithIcon("error", "", "获取角色信息失败");
        return;
      }

      this.setState({
        // treeData: (datas || []).map(item => { item.isLeaf = true; return item; }),
        // selectedKeys: loadedSelectedKeys,
        listData: datas,
        totalCount,
      });
      // const newData = datas.map(sitem => {
      //   sitem.isLeaf = true;
      //   sitem.roleCode = sitem.roleCode || sitem.groupId;
      //   sitem.roleName = sitem.roleName || sitem.groupName;
      //   return sitem;
      // });
      // this.loadedKeys = this.loadedKeys.concat(newData);
      // this.setState({treeData: newData});
      // this.setTreeSelectData(this.selectedKeysInvert, this.selectData);
    });
  };

  getUserGroupList = () => {
    const {dispatch} = this.props;
    const {pageNum, pageSize, keyWord} = this.state;
    if (!dispatch) return;
    dispatch({
      type: "FlowChart/getUserGroupPageList",
      payload: {groupName: keyWord, pageNo: pageNum, pageSize},
    }).then(({errCode, datas = [], totalCount = 0}) => {
      if (errCode !== 0) {
        this.openNotificationWithIcon("error", "", "获取用户组信息失败");
        return;
      }

      this.setState({
        // treeData: (datas || []).map(item => { item.isLeaf = true; return item; }),
        // selectedKeys: loadedSelectedKeys,
        listData: datas,
        totalCount,
      });
      // const newData = datas.map(sitem => {
      //   sitem.isLeaf = true;
      //   sitem.groupCode = sitem.groupCode;
      //   sitem.groupName = sitem.groupName;
      //   return sitem;
      // });
      // this.loadedKeys = this.loadedKeys.concat(newData);
      // this.setState({treeData: newData});
      // this.setTreeSelectData(this.selectedKeysInvert, this.selectData);
    });
  };

  getPositionList = () => {
    const {dispatch} = this.props;
    const {pageNum, pageSize, keyWord} = this.state;
    if (!dispatch) return;
    dispatch({
      type: "FlowChart/getUserPositionPageList",
      payload: {positionName: keyWord, pageNo: pageNum, pageSize},
    }).then(({errCode, datas = [], totalCount = 0}) => {
      if (errCode !== 0) {
        this.openNotificationWithIcon("error", "", "获取岗位信息失败");
        return;
      }

      this.setState({
        // treeData: (datas || []).map(item => { item.isLeaf = true; return item; }),
        // selectedKeys: loadedSelectedKeys,
        listData: datas,
        totalCount,
      });
      // const newData = datas.map(sitem => {
      //   sitem.isLeaf = true;
      //   sitem.positionCode = sitem.positionCode;
      //   sitem.positionName = sitem.positionName;
      //   return sitem;
      // });
      // this.loadedKeys = this.loadedKeys.concat(newData);
      // this.setState({treeData: newData});
      // this.setTreeSelectData(this.selectedKeysInvert, this.selectData);
    });
  };

  getUserRelationShipList = () => {
    const {dispatch, appId} = this.props;
    if (!dispatch) return;
    dispatch({
      type: "FlowChart/getUserRelationShipList",
      payload: appId ? {appId} : {},
    }).then(({errCode, datas = []}) => {
      if (errCode !== 0) {
        this.openNotificationWithIcon("error", "", "获取关系信息失败");
      }
      const newData = datas.map(sitem => {
        sitem.isLeaf = true;
        sitem.shipType = sitem.shipType;
        sitem.shipName = sitem.shipName;
        return sitem;
      });
      this.loadedKeys = this.loadedKeys.concat(newData);
      this.setState({treeData: newData});
      this.setTreeSelectData(this.selectedKeysInvert, this.selectData);
    });
  };

  getAllFunctionConfigList = () => {
    const {dispatch, appId} = this.props;
    if (!dispatch) return;
    dispatch({
      type: "FlowChart/getAllFunctionConfigList",
      payload: appId ? {appId} : {},
    }).then(({errCode, datas = []}) => {
      if (errCode !== 0) {
        this.openNotificationWithIcon("error", "", "获取自定义函数信息失败");
      }
      const newData = datas.map(sitem => {
        sitem.isLeaf = true;
        sitem.id = sitem.id;
        sitem.functionName = sitem.functionName;
        return sitem;
      });
      this.loadedKeys = this.loadedKeys.concat(newData);
      this.setState({treeData: newData});
      this.setTreeSelectData(this.selectedKeysInvert, this.selectData);
    });
  };

  setTreeSelectData = (selectedKeys = [], selectData = []) => {
    const {type} = this.props;
    this.selectData = selectData;
    this.selectedKeysInvert = selectedKeys; // 需要反显的数据
    let newSelectedKeys = [];
    if (type === "ORG") {
      newSelectedKeys = selectedKeys.filter(item =>
        this.loadedKeys.some(citem => citem.code === item),
      );
    } else if (type === "STA") {
      newSelectedKeys = selectedKeys.filter(item =>
        this.loadedKeys.some(citem => citem.code === item),
      );
    } else if (type === "ROL") {
      newSelectedKeys = selectedKeys.filter(item =>
        this.loadedKeys.some(citem => citem.roleCode === item),
      );
    } else if (type === "GROUP") {
      newSelectedKeys = selectedKeys.filter(item =>
        this.loadedKeys.some(citem => citem.groupCode === item),
      );
    } else if (type === "POSITION") {
      newSelectedKeys = selectedKeys.filter(item =>
        this.loadedKeys.some(citem => citem.positionCode === item),
      );
    } else if (type === "RELATIONSHIP") {
      newSelectedKeys = selectedKeys.filter(item =>
        this.loadedKeys.some(citem => citem.shipType === item),
      );
    } else if (type === "FUNCTION") {
      newSelectedKeys = selectedKeys.filter(item =>
        this.loadedKeys.some(citem => citem.id === item),
      );
    }
    this.setState({selectedKeys: newSelectedKeys});
  };

  getSelectData = () => {
    const {type} = this.props;
    const res = [];
    this.selectData.forEach(item => {
      if (item.props) {
        const {
          props: {dataRef},
        } = item;
        if (dataRef.code && type === "STA") {
          // 用户
          if (dataRef.isLeaf) {
            res.push({type, code: dataRef.code, name: dataRef.displayName});
          }
        } else if (dataRef.code && type === "ORG") {
          // 角色
          res.push({type, code: dataRef.code, name: dataRef.displayName});
        } else if (dataRef.roleCode && type === "ROL") {
          // 组织
          res.push({type, code: dataRef.roleCode, name: dataRef.roleName});
        } else if (dataRef.groupCode && type === "GROUP") {
          // 用户组
          res.push({type, code: dataRef.groupCode, name: dataRef.groupName});
        } else if (dataRef.positionCode && type === "POSITION") {
          // 岗位
          res.push({
            type,
            code: dataRef.positionCode,
            name: dataRef.positionName,
          });
        } else if (dataRef.shipType && type === "RELATIONSHIP") {
          // 岗位
          res.push({type, code: dataRef.shipType, name: dataRef.shipName});
        } else if (dataRef.id && type === "FUNCTION") {
          // 自定义函数
          res.push({type, code: dataRef.id, name: dataRef.functionName});
        }
      } else if (item.code) {
        res.push(item);
      }
    });
    return res;
  };

  getTreeThis = () => {
    const {getTreeRef} = this.props;
    if (getTreeRef) getTreeRef(this);
  };

  onCheck = (checkedKeys, {checkedNodes, checked: ischecked, node}) => {
    // const { type } = this.props;
    const {checkStrictly = false, onCheckedNodes} = this.props;
    const {selectedKeys: prevSelectedKeys} = this.state;
    let selectedKeys = checkedKeys;
    if (checkStrictly) {
      const {checked = []} = checkedKeys;
      selectedKeys = checked;
    }
    this.selectData = checkedNodes;
    if (onCheckedNodes) {
      // 反回变化的项
      const newSelectNodes = this.getSelectData();
      onCheckedNodes(
        ischecked,
        node,
        checkedNodes,
        newSelectNodes,
        prevSelectedKeys,
      );
    }

    this.setState({selectedKeys});
  };

  handleLoadData = treeNode =>
    new Promise(resolve => {
      const {dispatch, isJustLoadOrg, type} = this.props;
      const {treeData, selectedKeys} = this.state;
      if (treeNode.props.children) {
        resolve();
        return;
      }
      const orgCode = treeNode.props.dataRef.code;
      const orgName = treeNode.props.dataRef.displayName;
      dispatch({
        type: "usertreeSelect/getChildren",
        isJustLoadOrg,
        payload: {pageNo: 1, pageSize: 1000, orgCode, orgName},
      }).then(({errCode, uerrCode, uerrMsg, errMsg, datas}) => {
        if (errCode !== 0) {
          this.openNotificationWithIcon(
            "error",
            "",
            errMsg || "获取子组织信息失败",
          );
        }
        if (uerrCode !== 0) {
          this.openNotificationWithIcon(
            "error",
            "",
            uerrMsg || "获取人员信息失败",
          );
        }
        if (datas.length > 0) {
          treeNode.props.dataRef.children = datas;
          // 反显处理
          let loadedSelectedKeys = [];
          if (type === "ORG") {
            loadedSelectedKeys = this.selectedKeysInvert.filter(item => {
              return datas.some(citem => citem.code === item);
            });
          } else {
            loadedSelectedKeys = this.selectedKeysInvert.filter(item => {
              return datas.some(citem => citem.code === item);
            });
          }
          const newKeys = [...selectedKeys, ...loadedSelectedKeys];
          this.loadedKeys = this.loadedKeys.concat(datas);
          this.setState({
            treeData: [...treeData],
            selectedKeys: newKeys,
          });
          resolve();
        }
        resolve();
      });
    });

  renderTreeNodes = data =>
    data.map(item => {
      const {isJustLoadOrg} = this.props;
      if (item.children) {
        return (
          <TreeNode
            disableCheckbox={!item.children}
            title={item.displayName}
            key={item.code}
            dataRef={item}
          >
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          disableCheckbox={!item.children && !item.isLeaf && !isJustLoadOrg}
          title={item.displayName}
          key={item.code}
          dataRef={item}
          isLeaf={item.isLeaf || false}
        />
      );
    });

  renderRolTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode
            disableCheckbox={!item.children}
            title={item.roleName}
            key={item.roleCode}
            dataRef={item}
          >
            {this.renderRolTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          title={item.roleName}
          key={item.roleCode}
          dataRef={item}
          isLeaf={item.isLeaf || false}
        />
      );
    });

  renderGroupTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode
            disableCheckbox={!item.children}
            title={item.groupName}
            key={item.groupCode}
            dataRef={item}
          >
            {this.renderGroupTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          title={item.groupName}
          key={item.groupCode}
          dataRef={item}
          isLeaf={item.isLeaf || false}
        />
      );
    });

  renderPositionTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode
            disableCheckbox={!item.children}
            title={item.positionName}
            key={item.positionCode}
            dataRef={item}
          >
            {this.renderPositionTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          title={item.positionName}
          key={item.positionCode}
          dataRef={item}
          isLeaf={item.isLeaf || false}
        />
      );
    });

  renderRelationshipTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode
            disableCheckbox={!item.children}
            title={item.shipName}
            key={item.shipType}
            dataRef={item}
          >
            {this.renderRelationshipTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          title={item.shipName}
          key={item.shipType}
          dataRef={item}
          isLeaf={item.isLeaf || false}
        />
      );
    });

  renderFunctionTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode
            disableCheckbox={!item.children}
            title={`${item?.functionName} = ${item?.functionUrl}`}
            key={item.id}
            dataRef={item}
          >
            {this.renderFunctionTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          title={`${item?.functionName} = ${item?.functionUrl}`}
          key={item.id}
          dataRef={item}
          isLeaf={item.isLeaf || false}
        />
      );
    });

  changePage = pageNum => {
    this.setState({pageNum}, () => {
      this.onSearch();
    });
  };

  changePageSize = (_, pageSize) => {
    this.setState({pageNum: 1, pageSize}, () => {
      this.onSearch();
    });
  };

  handleChange = e => {
    this.setState(
      {
        keyWord: e,
      },
      () => {
        this.onSearch();
      },
    );
  };

  onSearch = () => {
    const {type} = this.props;
    if (type === "STA") {
      this.searchEmployeeList();
    } else if (type === "ROL") {
      this.getCandidateGroups();
    } else if (type === "GROUP") {
      this.getUserGroupList();
    } else if (type === "POSITION") {
      this.getPositionList();
    }
  };

  searchEmployeeList = () => {
    const {dispatch} = this.props;
    const {pageNum, pageSize, keyWord} = this.state;
    dispatch({
      type: "usertreeSelect/selectEmployeeList",
      payload: {employeeName: keyWord, pageIndex: pageNum, pageSize},
    }).then(({errCode, errMsg, datas}) => {
      if (errCode === 0) {
        this.setState({
          // treeData: (datas || []).map(item => { item.isLeaf = true; return item; }),
          // selectedKeys: loadedSelectedKeys,
          listData: datas.dataList,
          totalCount: datas.total,
        });
      } else {
        this.openNotificationWithIcon("error", "", errMsg || "搜索失败");
      }
    });
  };

  clearSearch = () => {
    this.loadedKeys = [];
    this.setState({selectedKeys: [], treeData: []});
    this.getRootOrg();
  };

  onSelectChange = (selectedRowKeys, selectedRows) => {
    const {type} = this.props;
    if (type === "STA") {
      if (selectedRows.some(d => !d.userId)) {
        message.warning("userId为空，请核实用户数据");
        return;
      }
    } else if (type === "ROL") {
      if (selectedRows.some(d => !d.roleCode)) {
        message.warning("roleCode为空，请核实角色数据");
        return;
      }
    } else if (type === "GROUP") {
      if (selectedRows.some(d => !d.groupCode)) {
        message.warning("groupCode为空，请核实用户组数据");
        return;
      }
    } else if (type === "POSITION") {
      if (selectedRows.some(d => !d.positionCode)) {
        message.warning("positionCode为空，请核实用户组数据");
        return;
      }
    }
    this.handleSelected(selectedRowKeys, selectedRows);
  };

  handleSelected = selectedRowKeys => {
    const {type} = this.props;

    this.setState({selectedRowKeys});
    const {onCheckedRows, defaultSelectData = []} = this.props;
    const {listData} = this.state;
    // const { listSearchData } = usertreeSelectStore;
    const result = defaultSelectData
      .filter(d => d.type === type)
      .filter(d => selectedRowKeys.includes(d.code));
    listData.map(item => {
      if (type === "STA") {
        if (selectedRowKeys.includes(item.userId)) {
          result.push({
            type,
            code: item.userId,
            name: item.employeeName,
          });
        }
      } else if (type === "ROL") {
        if (selectedRowKeys.includes(item.roleCode)) {
          result.push({
            type,
            code: item.roleCode,
            name: item.roleName,
          });
        }
      } else if (type === "GROUP") {
        if (selectedRowKeys.includes(item.groupCode)) {
          result.push({
            type,
            code: item.groupCode,
            name: item.groupName,
          });
        }
      } else if (type === "POSITION") {
        if (selectedRowKeys.includes(item.positionCode)) {
          result.push({
            type,
            code: item.positionCode,
            name: item.positionName,
          });
        }
      }

      return null;
    });
    // defaultSelectData.map(item => {
    //   if (selectedRowKeys.includes(item.code)) {
    //     // result.push({type:'STA', code: item.code , name: item.name });
    //     result.push(item);
    //   }
    //   return null;
    // });
    if (onCheckedRows) {
      onCheckedRows(result, type);
    }
  };

  deleteData = (data = []) => {
    const {selectedRowKeys} = this.state;
    if (data.length === 0) {
      this.setState({
        selectedRowKeys: [],
      });
      return;
    }
    const resultData = [];
    selectedRowKeys.map(t => {
      if (!data.includes(t)) {
        resultData.push(t);
      }
      return null;
    });
    this.setState({
      selectedRowKeys: resultData,
    });
  };

  getTreeNodes = type => {
    const {treeData} = this.state;
    switch (type) {
      case "ORG":
        return this.renderTreeNodes(treeData);
      case "ROL":
        return this.renderRolTreeNodes(treeData);
      case "GROUP":
        return this.renderGroupTreeNodes(treeData);
      case "POSITION":
        return this.renderPositionTreeNodes(treeData);
      case "RELATIONSHIP":
        return this.renderRelationshipTreeNodes(treeData);
      case "FUNCTION":
        return this.renderFunctionTreeNodes(treeData);
      default:
        break;
    }
  };

  showModal = () => {
    this.setState({
      visible: true,
    });
  };


  onEdit = () => {
    const {selectedKeys, treeData} = this.state;
    const {form} = this.props;
    const formValue = treeData.filter(v => v.id === selectedKeys[0])[0]
    this.setState({
      visible: true,
    });
    setTimeout(() => form.setFieldsValue({
      functionName: formValue.functionName,
      functionUrl: formValue.functionUrl,
      functionCode: formValue.functionCode,
    }), 200);

  };

  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };

  handleOk = () => {
    const {form, dispatch, allSelectData} = this.props;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      dispatch({
        type: "FlowChart/saveFunctionConfig",
        payload: {...values},
      }).then(({errCode, errMsg}) => {
        if (errCode === 0) {
          if (allSelectData && allSelectData.length > 0){
            // eslint-disable-next-line array-callback-return
            allSelectData.map(v => {
              if(v.code === this.selectedKeysInvert[0]){
                v.name = values.functionName;
              }
            });
          }
          this.handleCancel();
          this.getAllFunctionConfigList();
        } else {
          this.openNotificationWithIcon("error", "", errMsg);
        }
      });
    });
  };

  handleDelete = (selectedKeys) => {
    
    if (selectedKeys.length === 0) {
      openNotificationWithIcon("warning", "", '请先选择要删除的数据');
    } else {
      const {dispatch, allSelectData, onSelectedDataChange} = this.props;
      if (!dispatch) return;
      dispatch({
        type: "FlowChart/deleteFunctionConfig",
        payload: {ids: selectedKeys},
      }).then(({errCode, errMsg}) => {
        if (errCode === 0) {
          if (allSelectData && allSelectData.length > 0) {
            const filteredData = allSelectData.filter(v => v.type === "FUNCTION" ? !selectedKeys.includes(v.code) : true);
            onSelectedDataChange(filteredData);
          }
          openNotificationWithIcon("success", "", "删除成功");
          this.getAllFunctionConfigList();
          // this.getSelectData();
          // this.setState({selectedKeys: []});
          // newSelectedKeys = selectedKeys.filter(item =>
          //   this.selectedKeys.some(citem => citem.id === item),
          // );
        } else {
          this.openNotificationWithIcon("error", "", errMsg);
        }
      });
    }
  };

  render() {
    const {
      treeData,
      selectedKeys,
      selectedRowKeys,
      pageNum,
      pageSize,
      listData,
      totalCount,
      columns,
      visible,
    } = this.state;
    const {
      loading: {effects},
      checkStrictly = false,
      type,
      directoryTree = false,
      form,
    } = this.props;
    const {getFieldDecorator} = form;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      // getCheckboxProps: (record) => ({
      //   disabled: !record.userId, // Column configuration not to be checked
      //   name: record.name,
      //   onClick:()=>{
      //     console.log(record)
      //   }
      // }),
    };
    const rootLoading =
      effects["usertreeSelect/getRootOrg"] ||
      effects["usertreeSelect/selectEmployeeList"];
    const RenderTree = directoryTree ? Tree.DirectoryTree : Tree;
    let placeholder = "请输入";
    let rowKey = "";
    if (type === "STA") {
      rowKey = "userId";
      placeholder = "请输入用户姓名或者工号";
    } else if (type === "ROL") {
      rowKey = "roleCode";
      placeholder = "请输入角色名称";
    } else if (type === "GROUP") {
      rowKey = "groupCode";
      placeholder = "请输入用户组名称";
    } else if (type === "POSITION") {
      rowKey = "positionCode";
      placeholder = "请输入岗位名称";
    }

    return (
      <Spin spinning={!!rootLoading}>
        <div className={styles.user_tree}>
          {type === "STA" ||
          type === "ROL" ||
          type === "GROUP" ||
          type === "POSITION" ? (
            <Search
              style={{margin: "12px 0", width: 232}}
              placeholder={placeholder}
              onSearch={this.handleChange}
              // onChange={this.handleChange}
            />
          ) : null}
          {type === "STA" ||
          type === "ROL" ||
          type === "GROUP" ||
          type === "POSITION" ? (
            <Table
              columns={columns}
              size="small"
              rowKey={rowKey}
              rowSelection={rowSelection}
              dataSource={listData}
              pagination={{
                size: "small",
                showSizeChanger: true,
                showQuickJumper: true,
                onChange: this.changePage,
                onShowSizeChange: this.changePageSize,
                pageSize,
                current: pageNum,
                total: totalCount,
                pageSizeOptions: ["6", "10", "20", "30"],
              }}
            />
          ) : null}
          {(type === "RELATIONSHIP" ||
            type === "FUNCTION" ||
            type === "ORG") && (
            <>
              {treeData.length > 0 && (
                <RenderTree
                  checkable
                  checkStrictly={checkStrictly}
                  loadData={this.handleLoadData}
                  onCheck={this.onCheck}
                  defaultSelectedKeys={selectedKeys}
                  defaultCheckedKeys={selectedKeys}
                  checkedKeys={selectedKeys}
                  selectedKeys={selectedKeys}
                >
                  {this.getTreeNodes(type)}
                </RenderTree>
              )}
              {type === "FUNCTION" ? (
                <Button
                  type="primary"
                  onClick={this.showModal}
                  style={{marginLeft: "25px"}}
                >
                  添加
                </Button>
              ) : (
                ""
              )}
              {type === "FUNCTION" && selectedKeys.length > 0 ? (
                <Button
                  type="primary"
                  onClick={this.onEdit}
                  style={{marginLeft: "25px"}}
                >
                  编辑
                </Button>
              ) : (
                ""
              )}
              {type === "FUNCTION" && selectedKeys.length > 0 ? (
                <Popconfirm
                  placement="top"
                  title="请确认是否删除当前选中函数"
                  onConfirm={() => {
                    // this.setState(
                    //   {},
                    //   () => {
                    //     this.handleDelete(selectedKeys);
                    //     this.forceUpdate();
                    //   },
                    // );
                    this.handleDelete(selectedKeys);
                  }}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button>删除</Button>
                </Popconfirm>
              ) : (
                ""
              )}
            </>
          )}
        </div>
        <Modal
          centered
          destroyOnClose
          visible={visible}
          title="新增自定义函数"
          onCancel={this.handleCancel}
          onOk={this.handleOk}
        >
          <Form layout="vertical">
            <Form.Item label="函数名称">
              {getFieldDecorator("functionName", {
                rules: [{required: true, message: "请输入函数名称"}],
              })(<Input />)}
            </Form.Item>
            <Form.Item label="函数地址">
              {getFieldDecorator("functionUrl", {
                visible: false,
                rules: [{required: true, message: "请输入函数地址"}],
              })(<Input />)}
            </Form.Item>
            <Form.Item>
              {getFieldDecorator("functionCode", {
                initialValue: "",
              })(<Input type='hidden' />)}
            </Form.Item>
          </Form>
        </Modal>
      </Spin>
    );
  }
}

export default TreeSelect;
